package com.fancy.learncenter.ui.activity.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.EnvUtils;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.AliPayDataBean;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.WXDataBean;
import com.fancy.learncenter.common.AndroidBug5497Workaround;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.StatusBarCompat;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.LoginActivity;
import com.fancy.learncenter.ui.activity.MainActivity;
import com.fancy.learncenter.ui.activity.PlayVedioActivity;
import com.fancy.learncenter.ui.callback.ReWebChomeClient;
import com.fancy.learncenter.ui.view.PayPopupWindow;
import com.fancy.learncenter.ui.view.SharePopupWindow;
import com.fancy.learncenter.utils.ImageUtil;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ProgressUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.utils.WXShareUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import fancy.hyypaysdk.pay.PayCallBack;
import fancy.hyypaysdk.pay.alipay.AliPayUtils;
import fancy.hyypaysdk.pay.wxpay.WXPayUtil;
import okhttp3.ResponseBody;
import retrofit2.Response;

public class MallCommonH5Activity extends BaseActivity implements ReWebChomeClient.OpenFileChooserCallBack {
    public static final String ERROR_URL = "file:///android_asset/weberror.html";
    public static String URL_KEY = "linkURL";
    private static final int REQUEST_CODE_PICK_IMAGE = 0;
    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
    private static final int REQUEST_LOAD_URL = 3;
    @Bind(R.id.mWebView)
    WebView mWebView;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.rootView)
    LinearLayout rootView;

    private String goUrl;
//    private String initURL = "";

    //解决重定向问题判断是否重开新的界面
    private boolean goH5 = true;

    private Intent mSourceIntent;
    private ValueCallback<Uri> mUploadMsg;
    private ValueCallback<Uri[]> mUploadMsg5;

    public Dialog errorDialog;


    PayPopupWindow payPopupWindow;

    SharePopupWindow sharePopupWindow;

    boolean loadFinshTitle = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_h5, Status.STATUS);
        ButterKnife.bind(this);
        initToolbar("");
        String url = getIntent().getStringExtra(URL_KEY);

        if (Constant.BECOME_TEACHER_URL.equals(url)) {
            goUrl = url;
        } else {
            goUrl = getLoadUrl(getIntent().getStringExtra(URL_KEY));
        }


        LogUtil.MyLog("URL_KEY", "=======goUrl===" + goUrl);
        initWebViewSetting();
        initWebViewClient();
        initWebViewChromeClient();
        initWebViewDown();
        mWebView.loadUrl(goUrl);
    }


    private void initWebViewSetting() {

//        WebSettings settings = mWebView.getSettings();
//        //支持JS
//        mWebView.getSettings().setJavaScriptEnabled(true);
//        //设置可访问文件
//        settings.setAllowFileAccess(true);
//        //设置适应屏幕
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
//        //支持缩放
//        settings.setSupportZoom(false);
//        //隐藏原生的缩放控件
//        settings.setDisplayZoomControls(false);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        }
//
//        //   设置缓存模式
//        settings.setAppCacheEnabled(true);
//        settings.setDatabaseEnabled(true);
//        settings.setDomStorageEnabled(true);//开启DOM缓存
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        settings.setAppCachePath(mWebView.getContext().getCacheDir().getAbsolutePath());
//
//        //支持自动加载图片
//        if (Build.VERSION.SDK_INT >= 19) {
//            settings.setLoadsImagesAutomatically(true);
//        } else {
//            settings.setLoadsImagesAutomatically(false);
//        }
//
//        settings.setJavaScriptCanOpenWindowsAutomatically(true);
//        settings.setBuiltInZoomControls(true);
//
//        mWebView.addJavascriptInterface(this, "mall");
//        mWebView.setDownloadListener(new DownloadListener() {
//            @Override
//            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//                Uri uri = Uri.parse(url);
//                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//                startActivity(intent);
//                MallCommonH5Activity.this.finish();
//            }
//        });


        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebView.getSettings().setAppCachePath(appCachePath);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setAppCacheEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //设置适应屏幕
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        //支持缩放
        mWebView.getSettings().setSupportZoom(false);
        //隐藏原生的缩放控件
        mWebView.getSettings().setDisplayZoomControls(false);

        mWebView.addJavascriptInterface(this, "hideTitleBar");
        mWebView.addJavascriptInterface(this, "mall");
        mWebView.addJavascriptInterface(this, "processShare");
        mWebView.addJavascriptInterface(this, "sendOrderMes");
        mWebView.addJavascriptInterface(this, "fslTitle");
        mWebView.addJavascriptInterface(this, "isShowHead");
        mWebView.addJavascriptInterface(this, "callNative");
        mWebView.addJavascriptInterface(this, "back");
        mWebView.addJavascriptInterface(this, "getAppVersion");


        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                MallCommonH5Activity.this.finish();
            }
        });


    }

    private boolean downYYB = false;

    private void initWebViewClient() {
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                dialogShow();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                LogUtil.MyLog("URL_KEY", "=======shouldOverrideUrlLoading===" + url);
//
//                if (goH5) {
//                    goUrl = url;
//                    return false;
//                }
//
//                if (!TextUtils.isEmpty(url)) {
//                    String urlPath = "";
//                    try {
//                        urlPath = URLDecoder.decode(url, "UTF-8");
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//
//                    Intent intent;
//                    intent = new Intent();
//                    intent.setClass(MallCommonH5Activity.this, MallCommonH5Activity.class);
//                    intent.putExtra(URL_KEY, urlPath);
//                    startActivity(intent);
//
//                    return true;
//                }
//                mWebView.loadUrl(url);
                //表 示已经处理了这次URL的请求


                if (goH5) {
                    goUrl = url;
                    return false;
                }

                if (!TextUtils.isEmpty(url)) {
                    String goURL = "";
                    try {
                        goURL = URLDecoder.decode(url, "UTF-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Intent intent;
//                    if (goURL.contains("/activity/myActivity.html")) {
//                        My.myActivity = true;
//                        intent = new Intent(MallCommonH5Activity.this, MainActivity.class);
//                        startActivity(intent);
////                        return true;
//                    } else if (FFApp.myOrder && goURL.contains("/order/myOrder.html")) {
//                        FFApp.myOrder = true;
//                        intent = new Intent(MallCommonH5Activity.this, MainActivity.class);
//                        startActivity(intent);
//                    }
                    //应用宝市场
                    if (goURL.startsWith("tmast://appdetails")) {
                        try {
                            Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(url));
                            startActivity(viewIntent);
                            downYYB = false;
                        } catch (Exception e) {
                            downYYB = true;
                            ToastUtil.show("请先下载应用宝");
                        }
                        return true;
                    } else if (!downYYB && goURL.startsWith("http://saweb.3g.qq.com/")) {
                        return true;

                    } else if (!downYYB && goURL.startsWith("http://wxz.myapp.com/")) {
                        Intent mintent = new Intent(Intent.ACTION_VIEW);
                        mintent.addCategory(Intent.CATEGORY_BROWSABLE);
                        mintent.setData(Uri.parse(url));
                        startActivity(mintent);

                        return true;
                    } else {
                        intent = new Intent();
                        intent.setClass(MallCommonH5Activity.this, MallCommonH5Activity.class);
                        intent.putExtra("url", goURL);
                        startActivity(intent);

                    }
                    return true;
                }

                mWebView.loadUrl(url);

                return false;
            }


            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }


            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                LogUtil.MyLog("URL_KEY", "====onReceivedError=====" + view.getTitle());
                dialogDismiss();
                view.loadUrl(ERROR_URL);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                try {
                    if (goUrl.equals(URLDecoder.decode(url, "utf-8"))) {
                        goH5 = false;
                    } else {
                        goH5 = true;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (errorDialog != null && errorDialog.isShowing()) {
                    errorDialog.dismiss();
                }

                if (loadFinshTitle) {
                    title.setText(view.getTitle());
                }
                LogUtil.MyLog("URL_KEY", "====onPageFinished=title=====" + view.getTitle());

                dialogDismiss();

                mWebView.loadUrl("javascript:window.mall.isInFsl()");
                mWebView.loadUrl("javascript:window.mall.processHTML(document.getElementById('J-fsl-title').value);");
            }
        });


    }

    private void initWebViewChromeClient() {
        mWebView.setWebChromeClient(new ReWebChomeClient(this));
    }

    private void initWebViewDown() {
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                MallCommonH5Activity.this.finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @JavascriptInterface
    public void hideTitleBar() {
        runOnUiThread(new Runnable() {
            public void run() {
            }
        });
    }

    /**
     * 获取标题
     */
    @JavascriptInterface
    public void fslTitle(final String titleStr) {
        loadFinshTitle = false;
        runOnUiThread(new Runnable() {
            public void run() {
                title.setText(titleStr);
                LogUtil.MyLog(URL_KEY, "====fslTitle======" + titleStr);
            }
        });
    }

    /**
     * 获取标题
     */
    @JavascriptInterface
    public void h5Title(final String titleStr) {
        loadFinshTitle = false;
        runOnUiThread(new Runnable() {
            public void run() {
                try {
                    final JSONObject titleJson = new JSONObject(titleStr);
                    title.setText(titleJson.getString("title"));
                    LogUtil.MyLog(URL_KEY, "====h5Title======" + titleJson.getString("title"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    /**
     * 获取标题
     */
    @JavascriptInterface
    public void processHTML(final String titleStr) {
        loadFinshTitle = false;
        runOnUiThread(new Runnable() {
            public void run() {
                LogUtil.MyLog(URL_KEY, "====fslTitle======" + titleStr);
                if (!TextUtils.isEmpty(titleStr)) {
                    title.setText(titleStr);
                }
            }
        });
    }

    // 拉起登录
    @JavascriptInterface
    public void fslLogin() {
        runOnUiThread(new Runnable() {
            public void run() {
                Intent intent = new Intent();
                intent.setClass(MallCommonH5Activity.this, LoginActivity.class);
                startActivity(intent);
                MallCommonH5Activity.this.finish();
            }
        });
    }

    @JavascriptInterface
    public boolean isInFsl() {
        return true;
    }

    @JavascriptInterface
    public void refresh() {
    }


    @JavascriptInterface
    public void isShowHead(final String str) {
        runOnUiThread(new Runnable() {
            public void run() {

                if (str.equals("true")) {
//                    topLayout.setVisibility(View.GONE);

                } else {

                }

            }
        });
    }


    // 掉起非凡学习本地支付（只支持商品和活动支付）
    @JavascriptInterface
    public void sendOrderMes(String str) {
        //支持商城支付回调
        LogUtil.MyLog(URL_KEY, "====sendOrderMes========" + str);

        try {
            final JSONObject payJson = new JSONObject(str);
            final String mallOrderNo = payJson.get("orderNo").toString();


            runOnUiThread(new Runnable() {
                public void run() {
                    if (payPopupWindow == null) {
                        payPopupWindow = new PayPopupWindow(MallCommonH5Activity.this, rootView);

                        payPopupWindow.setPayCallBack(new PayPopupWindow.PayCallBack() {
                            @Override
                            public void aliPay() {

                                PayType type;
                                if (payJson.isNull("isActivity")) {
                                    // 商品   调起本地支付回调
                                    type = PayType.goods;
                                } else {
                                    // 我的活动   调起本地支付回调
                                    type = PayType.acivity;
                                }
                                getPayData(mallOrderNo, "alipay", type);
                            }

                            @Override
                            public void wxPay() {

                                PayType type;
                                if (payJson.isNull("isActivity")) {
                                    // 商品   调起本地支付回调
                                    type = PayType.goods;
                                } else {
                                    // 我的活动   调起本地支付回调
                                    type = PayType.acivity;
                                }
                                getPayData(mallOrderNo, "wx", type);
                            }
                        });
                    }
                    payPopupWindow.showPopupWindow();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    // 掉起环球少年本地支付
    @JavascriptInterface
    public void pay(String str) {
        try {
            //支持商城支付回调
            LogUtil.MyLog(URL_KEY, "=======pay=====" + str);
            final JSONObject payJson = new JSONObject(str);
            final String mallOrderNo = payJson.get("orderNum").toString();
            final String payType = payJson.get("payType").toString();
            runOnUiThread(new Runnable() {
                public void run() {
                    if (payPopupWindow == null) {
                        payPopupWindow = new PayPopupWindow(MallCommonH5Activity.this, rootView);

                        payPopupWindow.setPayCallBack(new PayPopupWindow.PayCallBack() {
                            @Override
                            public void aliPay() {


                                PayType type = null;
                                if (payType.equals("lessonSignUp")) {
                                    // 商品   调起本地支付回调
                                    type = PayType.lessonSignUp;
                                } else if (payType.equals("goodsPay")) {
                                    // 我的活动   调起本地支付回调
                                    type = PayType.goods;
                                } else if (payType.equals("activityPay")) {
                                    // 我的活动   调起本地支付回调
                                    type = PayType.acivity;
                                }

                                // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);（测试沙箱）
                                getPayData(mallOrderNo, "alipay", type);
                            }

                            @Override
                            public void wxPay() {
                                PayType type = null;
                                if (payType.equals("lessonSignUp")) {
                                    // 商品   调起本地支付回调
                                    type = PayType.lessonSignUp;
                                } else if (payType.equals("goods")) {
                                    // 我的活动   调起本地支付回调
                                    type = PayType.goods;
                                } else if (payType.equals("activity")) {
                                    // 我的活动   调起本地支付回调
                                    type = PayType.acivity;
                                }
                                getPayData(mallOrderNo, "wx", type);
                            }
                        });
                    }
                    payPopupWindow.showPopupWindow();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //非凡学习APP分享
    @JavascriptInterface
    public void processShare(String str) {
        LogUtil.MyLog(URL_KEY, "====processShare========" + str);
        try {
            final JSONObject result = new JSONObject(str);

            final String title = result.getString("shareTitle");
            final String picUrl = result.getString("shareImageURL");
            final String content = result.getString("shareSubTitle");
            final String likUrl = result.getString("shareURL");

            runOnUiThread(new Runnable() {
                public void run() {
                    if (sharePopupWindow == null) {
                        sharePopupWindow = new SharePopupWindow(MallCommonH5Activity.this, rootView);
                        sharePopupWindow.setShareCallBack(new SharePopupWindow.ShareCallBack() {
                            @Override
                            public void wxCallBack() {
                                WXShareUtil.getInstance(MallCommonH5Activity.this).shareWebPage(picUrl, title, content, likUrl, false);
                            }

                            @Override
                            public void wxFriendCallBack() {
                                WXShareUtil.getInstance(MallCommonH5Activity.this).shareWebPage(picUrl, title, content, likUrl, true);
                            }
                        });
                    }
                    sharePopupWindow.showPopupWindow();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //环球少年APP分享（独有课程）
    @JavascriptInterface
    public void share(String str) {
        LogUtil.MyLog(URL_KEY, "====share========" + str);
        try {
            final JSONObject result = new JSONObject(str);

            final String title = result.getString("shareTitle");
            final String picUrl = result.getString("shareImageURL");
            final String content = result.getString("shareSubTitle");
            final String likUrl = result.getString("shareURL");

            runOnUiThread(new Runnable() {
                public void run() {
                    if (sharePopupWindow == null) {
                        sharePopupWindow = new SharePopupWindow(MallCommonH5Activity.this, rootView);
                        sharePopupWindow.setShareCallBack(new SharePopupWindow.ShareCallBack() {
                            @Override
                            public void wxCallBack() {
                                WXShareUtil.getInstance(MallCommonH5Activity.this).shareWebPage(picUrl, title, content, likUrl, false);
                            }

                            @Override
                            public void wxFriendCallBack() {
                                WXShareUtil.getInstance(MallCommonH5Activity.this).shareWebPage(picUrl, title, content, likUrl, true);
                            }
                        });
                    }
                    sharePopupWindow.showPopupWindow();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void back() {
        MallCommonH5Activity.this.finish();
    }


    @Override
    public void finish() {
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("about:blank");
            }
        });

        super.finish();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != Activity.RESULT_OK) {
            if (mUploadMsg != null) {
                mUploadMsg.onReceiveValue(null);
                mUploadMsg = null;
            } else if (mUploadMsg5 != null) {
                mUploadMsg5.onReceiveValue(null);
                mUploadMsg5 = null;
            }
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_IMAGE_CAPTURE:
            case REQUEST_CODE_PICK_IMAGE: {
                try {
                    if (mUploadMsg == null && mUploadMsg5 == null) {
                        return;
                    }
                    String sourcePath = ImageUtil.retrievePath(this, mSourceIntent, data);
                    if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {

                        break;
                    }
                    Uri uri = Uri.fromFile(new File(sourcePath));

                    if (mUploadMsg != null) {
                        mUploadMsg.onReceiveValue(uri);
                    } else if (mUploadMsg5 != null) {
                        mUploadMsg5.onReceiveValue(new Uri[]{uri});
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case REQUEST_LOAD_URL:
                mWebView.reload();
                break;
        }
    }

    @Override
    public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadMsg = uploadMsg;
        showOptions();
    }

    @Override
    public void openAndroid5FileChooserCallBack(ValueCallback<Uri[]> uploadMsg) {
        mUploadMsg5 = uploadMsg;
        showOptions();
    }

    //拉起相册上传照片
    public void showOptions() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setOnCancelListener(new ReOnCancelListener());
        alertDialog.setTitle("选择");
        alertDialog.setItems(R.array.options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            mSourceIntent = ImageUtil.choosePhoto();
                            startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
                        } else {
                            mSourceIntent = ImageUtil.takeBigPicture();
                            startActivityForResult(mSourceIntent, REQUEST_CODE_IMAGE_CAPTURE);
                        }
                    }
                }
        );
        alertDialog.show();
    }

    private class ReOnCancelListener implements DialogInterface.OnCancelListener {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMsg != null) {
                mUploadMsg.onReceiveValue(null);
                mUploadMsg = null;
            } else if (mUploadMsg5 != null) {
                mUploadMsg5.onReceiveValue(null);
                mUploadMsg5 = null;
            }
        }
    }


    /**
     * @param orderNo
     * @param payChannel wx(微信支付)  alipay(支付宝支付)
     * @param payType    lessonSignUp(课程支付)
     */
    private void getPayData(String orderNo, final String payChannel, final PayType payType) {

        Map map = new HashMap<>();
        map.put("orderNo", orderNo);
        map.put("payChannel", payChannel);
        HttpMehtod.getInstance().getPayData(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                //微信支付结果
                if (payChannel.equals("wx")) {
                    //解析数据
                    BaseBean<WXDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), WXDataBean.class);
                    //数据业务逻辑处理
                    CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                    callBack.setCallBack(new CustomNetCallBack.NetCallBack<WXDataBean>() {
                        @Override
                        public void success(WXDataBean dataBean) {
                            Gson gson = new Gson();
                            String jsonObject = gson.toJson(dataBean.getAppPayRequestData());

                            WXPayUtil.getInstance().wxPay(MallCommonH5Activity.this, jsonObject, new PayCallBack() {
                                @Override
                                public void paySuccess() {
                                    MallCommonH5Activity.this.mWebView.reload();
                                    ToastUtil.show("支付成功");
                                    Intent intent;
                                    switch (payType) {
                                        case goods:
                                            intent = new Intent(MallCommonH5Activity.this, MainActivity.class);
                                            intent.putExtra(MainActivity.START_KEY, MainActivity.MY_ORDER_CODE);
                                            startActivity(intent);
                                            break;
                                        case acivity:
                                            intent = new Intent(MallCommonH5Activity.this, MainActivity.class);
                                            intent.putExtra(MainActivity.START_KEY, MainActivity.MY_ACTIVITY_CODE);
                                            startActivity(intent);
                                            break;
                                        case lessonSignUp:
                                            intent = new Intent(MallCommonH5Activity.this, MainActivity.class);
                                            intent.putExtra(MainActivity.START_KEY, MainActivity.MY_LESSON_CODE);
                                            startActivity(intent);
                                            break;
                                    }

                                }

                                @Override
                                public void payFaild(String status) {
                                    MallCommonH5Activity.this.mWebView.reload();
                                    ToastUtil.show("支付失败");
                                }

                                @Override
                                public void payCancle() {
                                    MallCommonH5Activity.this.mWebView.reload();
                                    ToastUtil.show("支付取消");
                                }
                            });
                        }

                        @Override
                        public void fail(String errorCode) {

                        }
                    }).dealData();
                } else if (payChannel.equals("alipay")) {
                    //解析数据
                    BaseBean<AliPayDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), AliPayDataBean.class);
                    //数据业务逻辑处理
                    CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                    callBack.setCallBack(new CustomNetCallBack.NetCallBack<AliPayDataBean>() {
                        @Override
                        public void success(AliPayDataBean dataBean) {

                            LogUtil.MyLog("AliPayUtils", "===========AliPayUtils====" + dataBean.getAppPayRequestData());
                            AliPayUtils.getInstance().aliPay(MallCommonH5Activity.this, dataBean.getAppPayRequestData(), new PayCallBack() {
                                @Override
                                public void paySuccess() {
                                    ToastUtil.show("支付成功");

                                    Intent intent;
                                    switch (payType) {
                                        case goods:
                                            intent = new Intent(MallCommonH5Activity.this, MainActivity.class);
                                            intent.putExtra(MainActivity.START_KEY, MainActivity.MY_ORDER_CODE);
                                            startActivity(intent);
                                            break;
                                        case acivity:
                                            intent = new Intent(MallCommonH5Activity.this, MainActivity.class);
                                            intent.putExtra(MainActivity.START_KEY, MainActivity.MY_ACTIVITY_CODE);
                                            startActivity(intent);
                                            break;
                                        case lessonSignUp:
                                            intent = new Intent(MallCommonH5Activity.this, MainActivity.class);
                                            intent.putExtra(MainActivity.START_KEY, MainActivity.MY_LESSON_CODE);
                                            startActivity(intent);
                                            break;
                                    }
                                }

                                @Override
                                public void payFaild(String status) {
                                    ToastUtil.show("支付失败");
                                }

                                @Override
                                public void payCancle() {
                                    ToastUtil.show("支付取消");
                                }
                            });

                        }

                        @Override
                        public void fail(String errorCode) {

                        }
                    }).dealData();
                }

            }
        });
    }


    private String getLoadUrl(String url) {

        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(url);

        if (sbUrl.toString().contains("?")) {
            if (sbUrl.toString().contains("keyFrom=" + Constant.KEY_FR0M)) {

            } else {
                sbUrl.append("&keyFrom=" + Constant.KEY_FR0M);
            }
        } else {
            sbUrl.append("?keyFrom=" + Constant.KEY_FR0M);
        }
        return sbUrl.toString();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        finish();
        return super.onKeyDown(keyCode, event);
    }

    public enum PayType {
        goods, acivity, lessonSignUp
    }
}
